<template>
    <div class="info-head">
        <div class="page-box">
            <el-tooltip placement="bottom-start" effect="light" popper-class="pag-span">
                <div slot="content">
                    <p class="time">{{infoData.firstModifiedDate}}</p>
                    <p class="user">{{infoData.firstEditor}}</p>
                </div>
                <div class="pag" :class="{active: !nowLast, disabled: isEdit}" @click="searchHistoryTimes('first')">首次</div>
            </el-tooltip>
            <div class="line"></div>
            <el-tooltip placement="bottom-start" effect="light" popper-class="pag-span">
                <div slot="content">
                    <p class="time">{{infoData.lastModifiedDate}}</p>
                    <p class="user">{{infoData.lastEditor}}</p>
                </div>
                <div class="pag" :class="{active: nowLast, disabled: isEdit}" @click="searchHistoryTimes('last')">末次</div>
            </el-tooltip>
            <span class="tips">第{{infoData.lastEditNum}}次修改</span>
        </div>
        <div class="operate-box">
            <div class="sign">
                <p><span></span>强制</p>
                <p><span></span>疑似</p>
            </div>
            <btn-group :disabled="isEdit" :showBtn="showBtn"/>
            <el-button :disabled="isEdit || !nowLast" v-if="infoData.status !== 1" class="audit" type="primary" size="small" v-auth="{code: 100003000002}" @click="openEdit" style="margin-right: 0;">编辑</el-button>
            <el-button class="audit" type="primary" v-if="!(infoData.status !== 0 || isEdit || !nowLast)" size="small" v-auth="{code: 100003000001}" style="margin-right: 0;" @click="showDialogMRAudit">审核</el-button>
            <el-button class="audit" type="primary" size="small" @click="toCollect">{{isCollect ? '取消收藏' : '收藏'}}</el-button>
            <div class="pagination-btn">
                <el-button
                    :disabled="infoData.index === 1 || infoData.PrevId === '' || isEdit"
                    class="pre"
                    type="info"
                    icon="el-icon-arrow-left"
                    @click="seachPackageId('pre')"
                    size="small"></el-button>
                <span>{{infoData.index || 1}}&nbsp;</span><span>/&nbsp;{{infoData.count || 1}}</span>
                <el-button
                    :disabled="infoData.index === infoData.count || infoData.NextId === '' || isEdit"
                    class="next"
                    type="info"
                    icon="el-icon-arrow-right"
                    @click="seachPackageId('next')"
                    size="small"></el-button>
            </div>
        </div>
        <div v-if="isEdit" class="edit-btn-group">
            <el-button type="info" size="small" @click="cancelEdit">取消</el-button>
            <el-button type="primary" size="small" @click="sumbitEdit">提交</el-button>
            <el-button type="warning" size="small" @click="QCEdit">质控</el-button>
        </div>
        <el-dialog title="病案首页审核"
                   :close-on-click-modal="false"
                   :visible.sync="isShowMRAudit"
                   @close="closeDialogMRAudit"
                   center
                   width="800px">
            <el-form :model="MRAuditForm" :rules="auditRules" ref="auditMRForm" class="audit-ruleForm">
                <el-form-item prop="examineState" label="是否通过：">
                    <el-radio-group v-model="MRAuditForm.examineState">
                        <el-radio :label="1">审核通过</el-radio>
                        <el-radio :label="2">驳回</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="驳 回 至：" v-if="MRAuditForm.examineState === 2">
                    <div>住院医师</div>
                </el-form-item>
                <el-form-item prop="remark" label="驳回原因：" v-if="MRAuditForm.examineState === 2">
                    <el-input v-model="MRAuditForm.remark" size="small" placeholder="请输入驳回原因" type="textarea" :rows="3"></el-input>
                </el-form-item>
                <el-form-item label="上传图片：" style="margin-top: 20px" v-if="MRAuditForm.examineState === 2">
                    <el-upload
                        class="upload-img"
                        :class="imgList.length < 3 ? '' : 'none'"
                        ref="upload"
                        action=""
                        list-type="picture-card"
                        :file-list="imgList"
                        :limit="3"
                        :auto-upload="false"
                        :on-preview="handlePictureCardPreview"
                        :before-upload="beforeUpload"
                        :on-change="handleChange"
                        :on-remove="handleRemove">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                </el-form-item>
                <el-dialog :visible.sync="dialogImgVisible" :modal="false">
                    <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="closeDialogMRAudit">取 消</el-button>
                <el-button size="small" @click="submitMRAudit" type="primary">确 定</el-button>
                <div class="tips">
                    <p><i class="el-icon-info"></i>提示</p>
                    <p><span></span>“被驳回”表示该病案存在严重填写缺陷，须编辑修正；</p>
                    <p><span></span>经编辑保存后病案状态更新为“未审核”，可再次进入审核流程；</p>
                    <p><span></span>“审核通过”后，该病案将不可被编辑修改，不可被再次导入系统；</p>
                    <p><span></span>每次至多上传图片3张。</p>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {
        searchHistory,
        checkOverviewTop,
        checkOverviewTopQC,
        checkAuditTopQC,
        checkCollectTopQC
    } from '@/api/medical-records/info-head'
    import {collectMR} from '@/api/myMR/collect'
    import BtnGroup from '@/components/BtnGroup'
    import {Bus} from '@/utils/bus'

    export default {
        name: 'InfoHead',
        props: ['infoData'],
        model: {
            prop: 'infoData',
            event: 'changeInfoData'
        },
        data () {
            return {
                // 按钮显示
                showBtn: ['goBack'],
                // 病案号搜索
                form: {
                    bah: ''
                },
                // 类型选项
                typeOptions: [
                    {key: 0, value: '编码问题'},
                    {key: 1, value: '非编码问题'},
                    {key: 2, value: '评分问题'},
                    {key: 3, value: '统计问题'},
                    {key: 4, value: '其他问题'}
                ],
                // 当前是末次
                nowLast: true,
                rules: {
                    bah: [
                        {required: true, message: '请输入病案号', trigger: 'blur'}
                    ]
                },
                // 初始数据
                oldData: {},
                // 显示审核弹框
                isShowMRAudit: false,
                // 审核表单
                MRAuditForm: {
                    examineState: 1,
                    remark: ''
                },
                // 图片列表
                imgList: [],
                // buffer列表
                base64Arr: [],
                // 预览图片路径
                dialogImageUrl: '',
                // 显示预览图片
                dialogImgVisible: false,
                auditRules: {
                    remark: [
                        {required: true, message: '请输入驳回原因', trigger: ['blur', 'change']},
                        {min: 4, message: '最少输入4个字', trigger: ['blur', 'change']}
                    ]
                },
                isCollect: false,
                timer: null
            }
        },
        computed: {
            isEdit () {
                return this.$store.state.user.isEdit
            }
            // isCollect () {
            //     return this.infoData.isCollection
            // }
        },
        created () {
            let params = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
            this.nowLast = params.isLast
            this.timer = setInterval(() => {
                this.isCollect = this.infoData.isCollection
            })
        },
        methods: {
            /**
             * 打开审核弹框
             */
            showDialogMRAudit () {
                this.isShowMRAudit = true
                this.MRAuditForm.examineState = 1
                this.MRAuditForm.remark = ''
            },
            /**
             * 关闭审核弹框
             */
            closeDialogMRAudit () {
                this.imgList = []
                this.base64Arr = []
                if (this.$refs.upload) {
                    this.$refs.upload.clearFiles()
                }
                this.$refs['auditMRForm'].resetFields()
                this.isShowMRAudit = false
            },
            /**
             * 预览图片
             * @param file 文件对象
             */
            handlePictureCardPreview (file) {
                this.dialogImageUrl = file.url
                this.dialogImgVisible = true
            },
            /**
             * 移除图片
             */
            handleRemove (file, fileList) {
                this.imgList = fileList
            },
            /**
             * 文件上传成功
             */
            handleChange (file) {
                if (file.status === 'ready') {
                    this.imgList.push(file)
                    this.getBase64(file.raw).then(res => {
                        this.base64Arr.push(res)
                    })
                }
            },
            /**
             * 图片转base64
             * @param file 文件对象
             */
            getBase64 (file) {
                return new Promise(function (resolve, reject) {
                    let reader = new FileReader()
                    let imgResult = ''
                    reader.readAsDataURL(file)
                    reader.onload = function () {
                        imgResult = reader.result
                    }
                    reader.onerror = function (error) {
                        reject(error)
                    }
                    reader.onloadend = function () {
                        resolve(imgResult)
                    }
                })
            },
            /**
             * 图片转换
             * @param file 文件对象
             */
            imageProcessing (file) {
                let _this = this
                return new Promise(function (resolve) {
                    let reader = new FileReader()
                    reader.readAsArrayBuffer(file)
                    reader.onload = function () {
                        resolve(_this.buf2hex(reader.result))
                    }
                })
            },
            /**
             * buffer数组转byte
             * @param buffer buffer数组
             */
            buf2hex (buffer) {
                return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('')
            },
            /**
             * 图片上传前
             */
            beforeUpload (file) {
                let isLt10M = file.size / 1024 / 1024 < 10
                if (!isLt10M) {
                    this.$message.error('图片大小不能超过 10MB!')
                }
                return isLt10M
            },
            /**
             * 提交审核
             */
            submitMRAudit () {
                this.$refs['auditMRForm'].validate((valid) => {
                    if (valid) {
                        let params = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                        params.medicalRecordID = this.infoData.medicalRecordID
                        params.examineInfo = this.MRAuditForm
                        params.examineInfo.picture = this.base64Arr
                        let infoData = {
                            noneCodingError: [],
                            noneCodingWaring: [],
                            codingError: [],
                            codingWaring: [],
                            allDeduction: [],
                            DRGsData: {},
                            resExamine: []
                        }
                        this.checkOverviewData(params, infoData)
                    } else {
                        return false
                    }
                })
            },
            /**
             * 收藏或取消收藏
             */
            toCollect () {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                let params = {
                    medicalRecordID: this.infoData.medicalRecordID,
                    isLast: query.isLast
                }
                collectMR(params).then(res => {
                    if (res.code.toString() === '200') {
                        this.$message.success('操作成功')
                        let data = this.infoData
                        data.isCollection = !data.isCollection
                        this.$emit('changeInfoData', data)
                        sessionStorage.setItem(`${this.$route.name}QCInfo`, JSON.stringify(data))
                    }
                })
            },
            /**
             * 搜索病案历史
             * @param times 首次末次
             */
            searchHistoryTimes (times) {
                if (this.isEdit) return false
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                let params = {
                    medicalRecordSign: this.infoData.medicalRecordSign,
                    hospitalTime: Number(this.infoData.ZYCS),
                    isLast: times === 'last',
                    orgId: query.orgId
                }
                this.setGetStore(this.$route.name, {isLast: params.isLast})
                searchHistory(params).then(res => {
                    if (res.code.toString() === '200') {
                        this.nowLast = times === 'last'
                        let infoData = {
                            noneCodingError: [],
                            noneCodingWaring: [],
                            codingError: [],
                            codingWaring: [],
                            allDeduction: [],
                            DRGsData: {},
                            resExamine: [],
                            index: this.infoData.index,
                            count: this.infoData.count
                        }
                        let newData = res.data
                        let data = {
                            ...infoData,
                            ...newData
                        }
                        this.$emit('changeInfoData', data)
                        this.$emit('finishCheck', params, data.medicalRecordID)
                    } else {
                        this.$message.error(res.message)
                    }
                })
            },
            /**
             * 搜索病案号
             */
            searchData () {
                if (this.isEdit) return false
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        this.$emit('searchData', this.form.bah)
                    } else {
                        return false
                    }
                })
            },
            /**
             * 查询指定id数据
             */
            seachPackageId (type) {
                let index = ''
                if (type === 'next') {
                    index = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name])).pageIndex + 1
                } else if (type === 'pre') {
                    index = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name])).pageIndex - 1
                }
                this.$emit('getData', index)
            },
            /**
             * 去编辑表格
             */
            openEdit () {
                Bus.$emit('editTableInfo', 'open')
                this.$store.dispatch('user/changeEditState', true)
            },
            /**
             * 取消编辑
             */
            cancelEdit () {
                Bus.$emit('editTableInfo', 'cancel')
            },
            /**
             * 提交编辑
             */
            sumbitEdit () {
                Bus.$emit('editTableInfo', 'sumbit')
            },
            /**
             * 质控预览
             */
            QCEdit () {
                Bus.$emit('editTableInfo', 'qc')
            },
            /**
             * 审核
             */
            checkOverviewData (params, infoData) {
                if (this.$route.name === 'QCEffectInfo') {
                    checkOverviewTopQC(params).then(res => {
                        this.closeDialogMRAudit()
                        this.checkOverviewDataRes(res, infoData, params)
                    })
                } else if (this.$route.name === 'MyMRAuditInfo') {
                    checkAuditTopQC(params).then(res => {
                        this.closeDialogMRAudit()
                        this.checkOverviewDataRes(res, infoData, params)
                    })
                } else if (this.$route.name === 'MyMRCollectInfo') {
                    checkCollectTopQC(params).then(res => {
                        this.closeDialogMRAudit()
                        this.checkOverviewDataRes(res, infoData, params)
                    })
                } else {
                    checkOverviewTop(params).then(res => {
                        this.closeDialogMRAudit()
                        this.checkOverviewDataRes(res, infoData, params)
                    })
                }
            },
            /**
             * 审核后执行
             */
            checkOverviewDataRes (res, infoData, params) {
                if (res.code.toString() === '200') {
                    if (res.data && res.data.rows.length) {
                        let data = {
                            ...infoData,
                            ...res.data.rows[0],
                            index: res.data.index,
                            count: res.data.total
                        }
                        this.$emit('changeInfoData', data)
                        let query = {
                            medicalRecordSign: data.medicalRecordSign,
                            hospitalTime: Number(res.data.rows[0].hospitalTime),
                            isLast: params.isLast,
                            orgId: params.orgId
                        }
                        this.$emit('finishCheck', query, data.medicalRecordID)
                    } else {
                        this.$emit('changeInfoData', {...this.infoData, status: params.examineInfo.examineState === 1 ? 2 : 1})
                        let query = {
                            medicalRecordSign: this.infoData.BAH,
                            hospitalTime: Number(this.infoData.ZYCS),
                            isLast: params.isLast,
                            orgId: params.orgId
                        }
                        this.$emit('finishCheck', query, this.infoData.medicalRecordID)
                    }
                } else {
                    this.$message.error(res.message)
                }
            }
        },
        components: {
            BtnGroup
        },
        beforeDestroy () {
            this.timer = null
        }
    }
</script>

<style scoped lang="scss">
    .info-head {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        /*padding-bottom: 10px;*/
        border-bottom: 1px solid #bdbdbd;
        .page-box {
            width: calc(100% - 850px);
            display: flex;
            justify-content: flex-start;
            align-items: center;
            flex-wrap: wrap;
            margin: 10px 0 0 0;
            padding: 0;
            max-height: 80px;
            .pag {
                padding: 0 10px;
                height: 30px;
                background: #a2a3a4;
                line-height: 30px;
                text-align: center;
                border-radius: 4px;
                color: #fff;
                cursor: pointer;
                &.active {
                    background: #409eff;
                }
                &.disabled {
                    cursor: not-allowed;
                }
            }
            .line {
                width: 20px;
                height: 2px;
                background: #e4e7ed;
                margin: 0 4px;
            }
            .tips {
                font-size: 14px;
                color: #797979;
                margin-left: 20px;
            }
        }
        .operate-box {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            .sign {
                display: flex;
                justify-content: flex-start;
                align-items: center;
                p {
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;
                    margin-right: 10px;
                    color: #e21f06;
                    span {
                        display: block;
                        width: 12px;
                        height: 12px;
                        border-radius: 2px;
                        margin-right: 4px;
                        background: #e21f06;
                    }
                    &:nth-child(2) {
                        color: #ec7534;
                        span {
                            background: #ec7534;
                        }
                    }
                }
            }
            .audit {
                margin: 0 15px;
            }
            .pagination-btn {
                font-size: 14px;
                button {
                    height: 32px;
                    font-size: 14px;
                    margin-right: 6px;
                    &:last-child {
                        margin-left: 6px;
                        margin-right: 0;
                    }
                }
                & > span {
                    font-size: 16px;
                    &:nth-of-type(1) {
                        color: #409eff;
                    }
                }
            }
            .head-form {
                margin-left: 15px;
                .el-form-item {
                    margin-bottom: 0;
                    .head-input-search {
                        width: 160px;
                        .el-icon-search {
                            cursor: pointer;
                            height: 32px;
                        }
                    }
                }
            }
        }
    }
    .pag-span {
        .time {
            margin: 0 0 4px;
            color: #409eff;
            font-size: 14px;
        }
        .user {
            margin: 0;
            font-size: 14px;
        }
    }
    .edit-btn-group {
        position: fixed;
        width: 100%;
        left: 0;
        bottom: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1;
        background: #fff;
        height: 48px;
        button {
            margin: 0 20px;
            width: 80px;
        }
    }
    .dialog-footer {
        text-align: center;
        .tips {
            margin-top: 20px;
            text-align: left;
            padding: 10px 20px;
            border: 1px solid #D7D7D7;
            background: #F2F2F2;
            border-radius: 8px;
            p {
                color: #333;
                font-size: 14px;
                line-height: 24px;
                position: relative;
                padding-left: 20px;
                margin: 0;
                .el-icon-info {
                    color: #108EE9;
                    margin-right: 6px;
                }
                &:first-child {
                    padding-left: 0;
                }
                span {
                    position: absolute;
                    top: 9px;
                    left: 8px;
                    display: block;
                    width: 6px;
                    height: 6px;
                    border-radius: 50%;
                    background: #333;
                }
            }
        }
    }
    .upload-img {
        max-height: 159px;
        overflow: hidden;
        &.none {
            & > .el-upload.el-upload--picture-card {
                display: none;
            }
        }
    }
    /deep/.el-dialog__body {
        padding: 15px 25px 20px;
    }
    .el-form-item {
        margin: 0 20px 10px;
    }
    /deep/.el-form-item.is-required .el-form-item__label {
        margin-left: -10px;
    }
    .el-textarea {
        width: 80%;
    }
    /deep/.el-form-item__error {
        left: 82px;
    }
</style>
